<?php

//constants for parsing
$m1 = "DESCRIPTION:";	//marker 1
$m2 = "SUMMARY:"; 		//marker 2
$m3 = "END:VEVENT"; 	//marker 3

//given the lines of a .ics file this will add the classes to a given user id
function parseAddClasses($user, $cal_url, $sem = NULL)
{
  global $m1, $m2, $m3;

  if($sem === NULL)
    $sem = $GLOBALS["semester"];

	$classes = array(); //store classes we've added so duplicates on the schedule don't
	                    // get added into the db twice
	$valid = false; 		//have we found a valid class yet
	$course = '';
	$className = '';

  $lines = fileToLines($cal_url);
	if(count($lines) <= 0)
	 return false;
	 
 //clear all existing classes
 mysql_query("DELETE FROM Student_Class WHERE uid = '$user' AND semester='$sem'");
	
 //loop through lines
 foreach($lines as $line)
 {
  if(strncmp($line, $m1, strlen($m1)) == 0) //marker 1 starts a class name
   $className = stripQuotes(substr($line, strlen($m1)));
  else if(strncmp($line, $m2, strlen($m2)) == 0) //marker 2 starts a class summary
   $course = addslashes(stripQuotes(substr($line, strlen($m2))));
  else if(strncmp($line, $m3, strlen($m3)) == 0) //marker 3 ends the event
  {
    //add the course - lectures are not separate classes
   $course_num = courseName($course);
   if($course_num !== NULL)
   {
    $valid = true; //valid class found

		//get the reference name
		$o_course = getRefName($course_num);
		if($o_course !== NULL && $o_course != 0)
		{
		 $dep = floor($o_course / 1000);
		 $n = $o_course  % 1000;
		 $section = getSection($course);
		 if($dep < 10)
		  $course = '0' . $dep . '-' . $n . ' ' . $section;
		 else
		  $course = $dep . '-' . $n . ' ' . $section;
		}

		//add the class if it doesn't exist, otherwise grab its class id
    $cid = 0;
    $res = mysql_query("SELECT ID FROM Class WHERE Course='$course'");
    $crow = mysql_fetch_array($res, MYSQL_ASSOC);
    if($crow)
     $cid = $crow['ID'];
    else
    {
     mysql_query("INSERT INTO Class (Course, Description) VALUES ('$course', '$className')");
     $cid = mysql_insert_id();
    }
    
    //don't add a given class more than once
    if(!array_key_exists($course, $classes)) {
     mysql_query("INSERT INTO Student_Class (Class_ID, uid, semester) VALUES ('$cid', '$user', '$sem')");
     $classes[$course] = true;
    }     
   }
   
  }
 }

 return $valid;
}

//grab a file and explode its lines
function fileToLines($cal_url)
{
	$ch = curl_init(stripslashes($cal_url) . ".ics");
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	$data = curl_exec($ch);
	curl_close($ch);
	
	return explode("\n", $data);
}

//strip quotes from the string if they exist
function stripQuotes($str)
{
 $chars = " \t\n\r\0\x0B\"";
 return trim($str, $chars);
}


//returns the course name only (no recitation) for a given valid section
// returns NULL if the given name describes a lecture
// example valid course names: '15-213 B' => '15-213', 'Mini: 21-123 B1' => '21-123'
// exam. invalid course names: ['15-213 Lec 1', '36-309 Lec', 'Mini: 21-123 Lec 11'] => NULL
function courseName($name)
{
 if(strlen($name) <= 4)
  return NULL;

 if(strpos($name, 'Final Exam') !== false)
 {
  return NULL;
 }

 $parts = explode(' ', $name);
 if(substr($name, 0, 6) === 'Mini: ')
 {  
  if(ctype_digit(substr($name, -2, 1)))
   return NULL;
  
  foreach($parts as $piece)
   if($piece == 'Lec')
    return NULL;
    
  return $parts[1];
 }
 
 if(ctype_digit(substr($name, -1)))
  return NULL;
  
 if(substr($name, strlen($name) - 4) === ' Lec')
  return NULL;
 
 return $parts[0];
}

function getSection($name)
{
 $parts = explode(' ', $name);
 
 if(!$parts)
  return "";
 
 return $parts[count($parts) - 1];
}

 //return the reference name of a class - the lowest crosslinked class numerically
 function getRefName($name)
 {
  $name = str_replace(array(' ', '-'), '', $name);
  
  $res = mysql_query("SELECT RefClass FROM crosslist WHERE Class='$name'");
  if(!$res)
   return $name;
   
  $row = mysql_fetch_array($res, MYSQL_ASSOC);
  if($row['RefClass'])
   return $row['RefClass'];
  
  return NULL;
 }
 
?>
